package com.ruoyi.project.secret.service.impl;

import com.ruoyi.project.secret.config.SecretConfig;
import com.ruoyi.project.secret.constant.SecretConstant;
import com.ruoyi.project.secret.domain.SecretBase;
import com.ruoyi.project.secret.domain.SecretResult;
import com.ruoyi.project.secret.service.SecretServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Squbi
 */
@Service
public class SecretServerImpl implements SecretServer {
    private static final Logger logger = LoggerFactory.getLogger(SecretServerImpl.class);

    private final SecretConfig secretConfig;

    private final RestTemplate restTemplate;
    private SecretBase secretBase;

    public SecretServerImpl(SecretConfig secretConfig) {
        this.secretConfig = secretConfig;
        this.restTemplate = new RestTemplate();
//        runListen();
    }

    @Override
    public void flushSecretInfo() {
        String requestAddress = SecretConstant.GET_SECRET.toAddress(secretConfig.getSecretAddress());
        try {
            this.secretBase = restTemplate.getForObject(requestAddress, SecretBase.class);
            logger.debug("secret base flushed to : {}", this.secretBase);
        } catch (Exception e) {
            this.secretBase = null;
        }
    }

    @Override
    public void runListen() {
        new Thread(() -> {
            try {
                while (true) {
                    flushSecretInfo();
                    Thread.sleep(1000 * 60);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } finally {
                this.secretBase = null;
            }
        }).start();
    }

    @Override
    public SecretBase getSecretBase() {
        if (this.secretBase == null) {
            flushSecretInfo();
            if (this.secretBase == null) {
                throw new RuntimeException("Secret认证服务错误");
            }
        }
        return this.secretBase;
    }

    @Override
    public String leftTime() {
        Date tar = new Date();
        tar.setTime(new Date().getTime() + (getSecretBase().getTotal() - getSecretBase().getUsed()) * 1000);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(tar);
    }

    @Override
    public SecretResult pushCode(String code) {
        String requestAddress = SecretConstant.POST_SECRET.toAddress(secretConfig.getSecretAddress());
        SecretResult secretResult = restTemplate.postForObject(requestAddress, code, SecretResult.class);
        logger.debug("push code secret result {}", secretResult);
        if (secretResult != null && secretResult.getCode() == 200) {
            flushSecretInfo();
        }
        return secretResult;
    }
}
